import 'dart:convert';

import '../../user/model/EcyUserModel.dart';
import 'EcyLogger.dart';
import 'EcyStorage.dart';

class EcyUserUtil {
  static const kLoginedUserInfo = "kLoginedUserInfo";
  static EcyUserModel userModel = EcyUserModel("");
  factory EcyUserUtil() => _instance;
  static late final EcyUserUtil _instance = EcyUserUtil._internal();
  EcyUserUtil._internal() {
    print("EcyUserUtil init");
  }

  static void saveLoginedData(EcyUserModel userModel) async {
    if (userModel != null) {
      await EcyStorage.setString(kLoginedUserInfo, json.encode(userModel));
    } else {
      EcyLogger.log("saveLoginedData 数据null");
    }
  }

  static Future<EcyUserModel?> getLoginedUserInfo() async {
    String? value = await EcyStorage.getString(kLoginedUserInfo);
    if (value != null) {
      EcyUserModel logined = EcyUserModel.fromJson(json.decode(value));
      EcyUserUtil.userModel = logined;
      return logined;
    }
    return null;
  }

  static Future<EcyUserModel> getLoginedUserInfo2() async {
    String? value = await EcyStorage.getString(kLoginedUserInfo);
    if (value != null) {
      EcyUserModel logined = EcyUserModel.fromJson(json.decode(value));
      return logined;
    }
    return EcyUserModel("");
  }

  static Future<bool> logined() async {
    String? value = await EcyStorage.getString(kLoginedUserInfo);
    if (value != null) {
      EcyUserModel logined = EcyUserModel.fromJson(json.decode(value));
      return logined.token.isNotEmpty;
    }
    return false;
  }

  static void clearUserInfo() {
    userModel = EcyUserModel("");
    EcyStorage.remove(kLoginedUserInfo);
  }
}
